﻿using System;

namespace Cherry.Agile.RpcService.Client
{
    /// <summary>
    /// 客户端请求工厂类(静态单一处理模块方式)
    /// </summary>
    public class ServiceRequestFactory
    {
        /// <summary>
        /// 当前服务处理过程（单例）
        /// </summary>
        private static IClientProcessor CurrentProcessor;

        /// <summary>
        /// 第一步：创建服务
        /// </summary>
        /// <typeparam name="TProcessor">服务处理协议模块</typeparam>
        /// <param name="url">服务地址</param>
        public static void CreateService<TProcessor>(string url) where TProcessor:IClientProcessor,new()
        {
            if (CurrentProcessor == null)
                CurrentProcessor = new TProcessor();
            CurrentProcessor.ServiceUrl = url;
        }

        /// <summary>
        /// 第二步：创建验证Token
        /// </summary>
        /// <param name="token">Token</param>
        public static void CreateToken(string token)
        {
            if (CurrentProcessor == null)
                throw new NullReferenceException("CreateService first");
            CurrentProcessor.Token = token;
        }

        /// <summary>
        /// 第二步：创建请求
        /// </summary>
        /// <typeparam name="TRequest">ClientRequest请求类</typeparam>
        /// <returns></returns>
        public static TRequest CreateRequest<TRequest>() where TRequest: ClientRequest, new()
        {
            if (CurrentProcessor == null)
                throw new NullReferenceException("CreateService first");
            TRequest request=new TRequest();
            request.Processor = CurrentProcessor;
            return request;
        }


        /// <summary>
        /// 创建请求（每实例）
        /// </summary>
        /// <typeparam name="TRequest">ClientRequest请求类</typeparam>
        /// <returns></returns>
        public static TRequest CreateRequest<TProcessor,TRequest>(string url,string token)
            where TRequest: ClientRequest, new()
            where TProcessor:IClientProcessor,new()
        {
            TProcessor clientProc = new TProcessor();
            clientProc.ServiceUrl = url;
            clientProc.Token = token;
            TRequest request = new TRequest();
            request.Processor = clientProc;
            return request;
        }
    }
}
